import type { ImageMetadata } from '../types/models';

/**
 * Parse and validate metadata from JSON string
 * @param jsonString JSON string containing metadata
 * @returns Object with validation result and parsed metadata
 */
export function parseMetadata(jsonString: string): { 
  valid: boolean; 
  metadata?: ImageMetadata; 
  message?: string 
} {
  try {
    // Parse JSON
    const data = JSON.parse(jsonString);
    
    // Check if metadata has the required fields
    if (!data.version || !data.timestamp || !data.stitchedImageSize || !data.images) {
      return { valid: false, message: '元数据格式无效，缺少必要字段' };
    }
    
    // Check if metadata version is supported
    if (data.version !== '1.0') {
      return { valid: false, message: `不支持的元数据版本: ${data.version}` };
    }
    
    // Check if metadata has at least one image
    if (!Array.isArray(data.images) || data.images.length === 0) {
      return { valid: false, message: '元数据不包含任何图片信息' };
    }
    
    // Check if stitchedImageSize has width and height
    if (typeof data.stitchedImageSize.width !== 'number' || 
        typeof data.stitchedImageSize.height !== 'number') {
      return { valid: false, message: '元数据中的图片尺寸无效' };
    }
    
    // Check if all images have the required fields
    for (const img of data.images) {
      if (typeof img.id !== 'string' || 
          typeof img.name !== 'string' || 
          typeof img.x !== 'number' || 
          typeof img.y !== 'number' || 
          typeof img.width !== 'number' || 
          typeof img.height !== 'number' || 
          typeof img.format !== 'string') {
        return { valid: false, message: '元数据中的图片信息无效' };
      }
    }
    
    return { valid: true, metadata: data as ImageMetadata };
  } catch (error: any) {
    return { valid: false, message: `解析元数据时出错: ${error.message}` };
  }
}

/**
 * Validate if metadata matches the image dimensions
 * @param metadata Metadata to validate
 * @param imageWidth Image width
 * @param imageHeight Image height
 * @returns Object with validation result and error message
 */
export function validateMetadataDimensions(
  metadata: ImageMetadata, 
  imageWidth: number, 
  imageHeight: number
): { valid: boolean; message?: string } {
  // Allow for small differences in dimensions (e.g., due to compression)
  const widthDiff = Math.abs(imageWidth - metadata.stitchedImageSize.width);
  const heightDiff = Math.abs(imageHeight - metadata.stitchedImageSize.height);
  
  if (widthDiff > 10 || heightDiff > 10) {
    return { 
      valid: false, 
      message: `图片尺寸 (${imageWidth}x${imageHeight}) 与元数据中的尺寸 (${metadata.stitchedImageSize.width}x${metadata.stitchedImageSize.height}) 不匹配` 
    };
  }
  
  // Check if all image positions are within the bounds of the stitched image
  for (const imgPos of metadata.images) {
    if (imgPos.x < 0 || imgPos.y < 0 || 
        imgPos.x + imgPos.width > metadata.stitchedImageSize.width || 
        imgPos.y + imgPos.height > metadata.stitchedImageSize.height) {
      return { 
        valid: false, 
        message: `图片位置超出拼接图片范围: ${imgPos.name} (${imgPos.x}, ${imgPos.y}, ${imgPos.width}, ${imgPos.height})` 
      };
    }
  }
  
  return { valid: true };
}